<template>
    <el-select
            ref="elSelect"
            :value="value"
            v-bind="originProp"
            :disabled="disabled"
            :readonly="readonly"
            clearable
            filterable
            :loading="loading"
            @dblclick.native="dblclick"
            :remote-method="remoteMethod"
            v-on:focus="($event)=>{$emit('focus', $event)}"
            v-on:blur="($event)=>{$emit('blur', $event)}"
            v-on:change="(val)=>{$emit('change', val)}"
            v-on:input="(val)=>{$emit('input', val)}"
    >
        <template v-if="!isGroup && localData && localData.length > 0">
            <el-option
                    v-for="(item) in localData"
                    :label="$stObjectTools.getValue(item,optionProp.label)"
                    :disabled="!!item.disabled"
                    :value="$stObjectTools.getValue(item,optionProp.value)"
                    :key="$stObjectTools.getValue(item,optionProp.value)"
            ></el-option>
        </template>
        <template v-else-if="isGroup && localData && localData.length > 0">
            <el-option-group
                    v-for="(groupItem,groupItemIndex) in localData"
                    :key="groupItemIndex"
                    :label="$stObjectTools.getValue(groupItem,optionProp.label)">
                <el-option
                        v-for="(item,index) in $stObjectTools.getValue(groupItem,optionProp.groupItems)"
                        :label="$stObjectTools.getValue(item,optionProp.label)"
                        :disabled="item.isDisabled || false"
                        :value="$stObjectTools.getValue(item,optionProp.value)"
                        :key="index"
                ></el-option>
            </el-option-group>
        </template>
    </el-select>
</template>

<script>
    let yesNoBool = [
        {
            id: true,
            name: '是'
        },
        {
            id: false,
            name: '否'
        },
    ]
    let yesNoNum = [
        {
            id: 1,
            name: '是'
        },
        {
            id: 0,
            name: '否'
        },
    ]
    export default {
        name: 'StElSelect',
        props: {
            value: {},
            // 被包装组件的原始属性
            originProp: {
                type: Object,
                default: function () {
                    return {}
                }
            },
            disabled: Boolean,
            readonly: Boolean,
            // 自定义数据
            datas: {
                type: [Array, String],
                default: function () {
                    return []
                }
            },
            // 远程获取的url
            remoteUrl: {
                type: String
            },
            // 远程获取的参数名称
            remoteQueryProp: {
                type: String,
            },
            // 是否组，是表示数据为分组数据，需要包含两级数据结构
            isGroup:{
                type: Boolean,
                default: false
            },
            // 选项配置
            optionProp: {
                type: Object,
                default: function () {
                    return {
                        value: 'id', // 选中的值属性
                        label: 'name', // 显示的值属性
                        groupItems: 'items'
                    }
                }
            },
        },
        data() {
            return {
                loading: false,
                localData: []
            }
        },
        mounted() {
            this.initData(this.datas)
        },
        methods: {
            selectedDataEmit(val){
                let d = this.getSelectData(val)
                this.$emit('data', d)
            },
            // 获取选中的数据本身
            getSelectData(val) {
                if (val == null || val == undefined) {
                    return null
                }
                let data = this.localData
                if(this.isGroup){
                    data = []
                    for (let i = 0; i < this.localData; i++) {
                        data = data.concat(this.$stObjectTools.getValue(this.localData[i],this.optionProp.groupItems)||[])
                    }
                }
                if(!this.$stArrayTools.isArray(val)){
                    return data.filter(item => val == this.$stObjectTools.getValue(item, this.optionProp.value)).pop() || null
                }
                return data.filter(item => val.some(valItem => valItem == this.$stObjectTools.getValue(item, this.optionProp.value)))
            },
            // 根据url加载数据
            initDataByUrl(url) {
                this.axios.get(url).then(res => {
                    this.localData = res.data
                    this.$nextTick(() => {if(this.$refs.elSelect) {this.$refs.elSelect.setSelected()}})
                }).catch(error => {
                    this.localData = []
                    if (error.response) {
                        if (error.response.status == 401) {
                            return
                        }
                        if (error.response.data && error.response.data.errorMsg) {
                            if (error.response.status != 404) {
                                this.$message.error(error.response.data.errorMsg);
                            }
                        }

                    } else {
                        this.$message.error('网络错误或服务不可用')
                    }
                })
            },
            // 加载
            initData(data) {
                if (!data) {
                    return
                }

                if (this.$stArrayTools.isArray(data)) {
                    this.localData = data;
                } else if (this.$stStringTools.isString(data)) {
                    if (!this.dataEnhance(data)) {
                        this.initDataByUrl(data);
                    }
                } else if (this.$stFunctionTools.isFunction(data)) {
                    this.initData(data());
                }
            },
            dataEnhance(data) {
                if (data === 'yesNoBool') {
                    this.localData = yesNoBool
                    return true
                }else if (data === 'yesNoNum') {
                    this.localData = yesNoNum
                    return true
                }
                return false
            },
            // 远程获取
            remoteMethod(query) {
                // 原生组件支持
                if (this.originProp && this.originProp.remoteMethod) {
                    this.originProp.remoteMethod(query)
                }else {
                    let p = {}
                    p[this.remoteQueryProp] = query
                    this.loading = true
                    this.axios.get(this.remoteUrl,{params: p}).then(res=>{
                        if (this.$stObjectTools.isObject(res.data)) {
                            this.initData(res.data.records);
                        }else{
                            this.initData(res.data);
                        }
                    }).finally(()=>{
                        this.loading = false
                    })
                }
            },
          dblclick(){
            this.initData(this.datas)
          }
        },
        watch: {
            datas(val) {
                this.initData(val)
            },
            value(val) {
                this.selectedDataEmit(val)
            },
            localData() {
                this.selectedDataEmit(this.value)
            }
        }
    }
</script>

<!-- Add "scoped" attribute to limit CSS to this component only -->
<style scoped>

</style>
